package com.wxzhou.wangzhuan.repository;

import com.wxzhou.wangzhuan.dto.config.AppConfig;
import io.smallrye.mutiny.Uni;
import io.vertx.mutiny.sqlclient.Pool;
import io.vertx.mutiny.sqlclient.Row;
import io.vertx.mutiny.sqlclient.Tuple;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;

import java.util.Optional;

@ApplicationScoped
public class ConfigRepository {

    private static final Logger LOG = Logger.getLogger(ConfigRepository.class);

    @Inject
    Pool client;

    /**
     * 根据配置键获取配置
     */
    public Uni<Optional<AppConfig>> getConfigByKey(String configKey) {
        return client.preparedQuery("SELECT * FROM wz_app_config WHERE config_key = $1")
                .execute(Tuple.of(configKey))
                .onItem().transform(rows -> {
                    if (rows.size() > 0) {
                        Row row = rows.iterator().next();
                        return Optional.of(mapRowToAppConfig(row));
                    }
                    return Optional.empty();
                });
    }

    /**
     * 将数据库行映射为AppConfig对象
     */
    private AppConfig mapRowToAppConfig(Row row) {
        AppConfig config = new AppConfig();
        config.setId(row.getLong("id"));
        config.setConfigKey(row.getString("config_key"));
        config.setConfigValue(row.getString("config_value"));
        config.setConfigType(row.getString("config_type"));
        config.setDescription(row.getString("description"));
        config.setCreatedAt(row.getLocalDateTime("created_at"));
        config.setUpdatedAt(row.getLocalDateTime("updated_at"));
        return config;
    }
}
